import NProgress from 'nprogress';
import React, { forwardRef, useEffect, useMemo } from 'react';
import type { MicroAppRef, MicroPortalWebProps } from '../../types';
import BasicMicroApp from './BasicMicroApp';

/**
 * PortalWeb微应用增强组件
 *
 * 功能特性：
 * - 继承 BasicMicroApp 的所有功能
 * - 集成 NProgress 进度条显示
 * - 支持进度条自定义配置
 * - 提供进度条事件回调
 * - 支持URL处理和路由解析
 */
const MicroPortalWeb = forwardRef<MicroAppRef, MicroPortalWebProps>(
  (
    {
      name,
      url,
      defaultPage: defaultPageProp,
      style,
      visible = true,
      showProgress = true,
      progressColor = '#1890ff',
      progressHeight = 2,
      progressOptions,
      onMounted,
      onAftershow,
      ...props
    },
    ref,
  ) => {
    // URL解析逻辑（来自sei-portal-web）
    const [entry, defaultPage] = useMemo(() => {
      const reg =
        /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\? i)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/;

      if (!reg.test(url.split('?')[0])) {
        const temp = url.split('/');
        const serviceName = temp[1];

        if (!temp.includes('#')) {
          return [`/${serviceName}/`, `#${url}`];
        }

        const route = url.split('#')[1];
        return [`/${serviceName}/`, `#${route}`];
      }

      return [url, defaultPageProp];
    }, [url, defaultPageProp]);

    // 初始化NProgress配置
    useEffect(() => {
      if (!showProgress) return;

      // 配置NProgress
      const config = {
        parent: `micro-app[name=${name}]`,
        showSpinner: false,
        ...progressOptions,
      };

      if (typeof document !== 'undefined' && document.body) {
        NProgress.configure(config);
      }

      // 设置进度条样式
      if (
        (progressColor || progressHeight) &&
        typeof document !== 'undefined' &&
        document.head
      ) {
        const style = document.createElement('style');
        style.innerHTML = `
          #nprogress .bar {
            background: ${progressColor} !important;
            height: ${progressHeight}px !important;
          }
          #nprogress .peg {
            box-shadow: 0 0 10px ${progressColor}, 0 0 5px ${progressColor} !important;
          }
        `;
        document.head.appendChild(style);

        // 清理函数
        return () => {
          if (document.head && document.head.contains(style)) {
            document.head.removeChild(style);
          }
        };
      }
    }, [name, showProgress, progressColor, progressHeight, progressOptions]);

    // 开始进度条
    useEffect(() => {
      if (showProgress && typeof document !== 'undefined' && document.body) {
        NProgress.start();
      }
    }, [showProgress]);

    // 处理挂载完成事件
    const handleMounted = (event: CustomEvent) => {
      if (showProgress && typeof document !== 'undefined' && document.body) {
        NProgress.done();
      }

      if (onMounted) {
        onMounted(event);
      }
    };

    // 处理推入前台事件
    const handleAftershow = (event: CustomEvent) => {
      if (showProgress && typeof document !== 'undefined' && document.body) {
        NProgress.done();
      }

      if (onAftershow) {
        onAftershow(event);
      }
    };

    // 组件样式
    const componentStyle: React.CSSProperties = {
      width: '100%',
      height: '100%',
      display: visible ? 'block' : 'none',
      ...style,
    };

    return (
      <BasicMicroApp
        ref={ref}
        name={name}
        url={entry}
        defaultPage={defaultPage}
        style={componentStyle}
        onMounted={handleMounted}
        onAftershow={handleAftershow}
        {...props}
      />
    );
  },
);

MicroPortalWeb.displayName = 'MicroPortalWeb';

export default MicroPortalWeb;
